package com.tedu.weibo.controller;

import com.tedu.weibo.mapper.UserMapper;
import com.tedu.weibo.pojo.dto.UserLoginDTO;
import com.tedu.weibo.pojo.dto.UserRegDTO;
import com.tedu.weibo.pojo.entity.User;
import com.tedu.weibo.pojo.entity.UserVO;
import com.tedu.weibo.result.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

import static com.tedu.weibo.result.Status.*;

@RestController
@RequestMapping("/v1/users")
@Slf4j
@Api(tags = "用户模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("/reg")
    @ApiOperation(value = "用户注册")
    public JsonResult reg(@RequestBody UserRegDTO userRegDTO){
        log.trace("UserController.reg() 开始被调用");
        log.debug("UserController.reg() 参数:{}",userRegDTO);
        log.info("开始处理用户注册");
        if(userMapper.selectByUsername(userRegDTO.getUsername())== null){
            User user = new User();
            BeanUtils.copyProperties(userRegDTO,user);
            log.debug("User: "+user);
            user.setCreated(new java.util.Date());
            userMapper.reg(user);
            log.trace("UserController.reg() 调用结束");
                return JsonResult.success();
        }
        log.trace("UserController.reg() 调用结束");
        return new JsonResult(USERNAME_EXIST);
    }

    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public JsonResult login(@RequestBody @Validated UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        System.out.println("开始处理登录请求:"+userLoginDTO);
        User user = userMapper.selectByUsername(userLoginDTO.getUsername());
        if(user == null){
            return new JsonResult(USERNAME_ERROR);
        }
        if(!user.getPassword().equals(userLoginDTO.getPassword())){
            return new JsonResult(PASSWORD_ERROR);
        }
        session.setAttribute("user",user);
        return  JsonResult.success();
    }


    @GetMapping("/currentUser")
    @ApiOperation(value = "获取当前登录用户")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        User user = (User) session.getAttribute("user");
        if(user == null){
            return new JsonResult(NOT_LOGIN);
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return JsonResult.success(userVO);
    }

    @ApiOperation(value = "用户登出")
    @GetMapping("/logout")
    public JsonResult logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return  JsonResult.success();
    }
}
